﻿using System.Linq;
using System.Web.Mvc;
using Pay.IService;
using Pay.TO;
using Pay.DTO;
using Pay.Core;
using System.Collections.Generic;
using System;
using System.IO;

namespace Pay.Web.Controllers {
    [RoutePrefix("common")]
    public class CommonController : GeneralController {
        private IRegionService _iReginService;
        private IFeatureService _iFeatureService;
        private IMerchantService _iMerchantService;
        private IManageService _iManageService;
        private ISettingService _iSettingService;

        public CommonController(IRegionService iReginService, IFeatureService iFeatureService,
                                IMerchantService iMerchantService, IManageService iManageService,
                               ISettingService iSettingService) {
            _iReginService = iReginService;
            _iFeatureService = iFeatureService;
            _iMerchantService = iMerchantService;
            _iManageService = iManageService;
            _iSettingService = iSettingService;
        }

        #region 验证码/短信
        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public FileResult Verify_code() {
            byte[] bytes = VerifyCode.ToByte();
            return File(bytes, "image/png");
        }
        #endregion

        #region 区域
        /// <summary>
        /// 查询全部省市区县
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1000000)]
        [AllowAnonymous]
        public JsonResult Regions() {
            //var list = _iReginService.GetAll();
            var list = _iReginService.Get();
            return Json(ResultToJson.Json("接收成功", list), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询全部省，市再省的children，区再市的children
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1000000)]
        [AllowAnonymous]
        [Route("get_regions")]
        public JsonResult GetRegion() {
            var list = _iReginService.GetAll();
            return Json(ResultToJson.Json("接收成功", list), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 查询省市区县
        /// </summary>
        /// <param name="id">id=0：表示省;；id=？：表示查此id所对的下级区域（可能市，可能区县，也有只有市没有区县的情况）</param>
        /// <returns></returns>
        [OutputCache(Duration = 1000000)]
        [AllowAnonymous]
        public JsonResult Region(long id) {
            var list = _iReginService.GetByParentId(id);
            return Json(list.Select(c => new { text = c.name, value = c.id }), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 功能菜单
        [Route("merchant_menus")]
        public JsonResult MerchantMenus() {
            var result = _iFeatureService.Get(FeatureType.Company);
            return Json(ResultToJson.Json("请求成功", result), JsonRequestBehavior.AllowGet);
        }

        [Route("admin_menus")]
        public ActionResult AdminMenus() {
            if (currentUser != null) {
                var result = _iFeatureService.GetByAdmin(currentUser.role_id, FeatureType.Admin);
                return Json(ResultToJson.Json("请求成功", result), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json("请求失败"), JsonRequestBehavior.AllowGet);
        }

        [Route("role_menus")]
        public ActionResult RoleMenus() {
            var result = _iFeatureService.GetByAdmin(currentUser.role_id);
            return Json(ResultToJson.Json("请求成功", result), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 平台设置
        [Route("site")]
        [AllowAnonymous]
        public JsonResult GetSite() {
            var site = _iSettingService.Get().site;
            if (currentUser != null) {
                if (currentUser.roles.Contains("Admin")) {
                    var manage = _iManageService.Get(currentUser.user_id);
                    return Json(ResultToJson.Json("接收成功", new {
                        site = site,
                        currentUser = new {
                            nick = manage.nick,
                            mobile = manage.mobile,
                            is_admin = true
                        },
                        token_api_url = t_RequestMethod.token_url
                    }), JsonRequestBehavior.AllowGet);
                } else {
                    merchant_dto member = _iMerchantService.Get(currentUser.user_id);
                    return Json(ResultToJson.Json("接收成功", new {
                        site = site,
                        currentUser = new {
                            nick = member.name,
                            mobile = member.mobile,
                            photo = member.photo
                        },
                        token_api_url = t_RequestMethod.token_url
                    }), JsonRequestBehavior.AllowGet);
                }
            }
            return Json(ResultToJson.Json("接收成功", new { site = site , token_api_url = t_RequestMethod.token_url }), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 银行
        [Route("banks")]
        [AllowAnonymous]
        public JsonResult Banks() {
            var list = typeof(BankCode).ToDictionary();
            var result = new List<use_bank>();
            list.ForEach(item => {
                result.Add(new use_bank { code = item.Key, name = item.Value });
            });
            return Json(ResultToJson.Json("接收成功", result), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 物流列表
        /// <summary>
        /// 物流列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Dictionary() {
            var result = RequestMethod.express;
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 文件
        /// <summary>
        /// 上传文件方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [Route("upload_file")]
        public JsonResult UploadFile(string id, bool is_editor = false) {
            if (Request.Files.Count == 0) {
                if (is_editor)
                    return Json(new { error = 1, message = "没有上传文件" }, JsonRequestBehavior.AllowGet);
                return Json(ResultToJson.Json<List<string>>("没有上传文件"), JsonRequestBehavior.AllowGet);
            }

            var result = UploadList(id);
            if (is_editor)
#if DEBUG
                return Json(new { error = 0, url = "http://testimg.epalpay.cn/" + result.First() }, JsonRequestBehavior.AllowGet);
#else
                return Json(new { error = 0, url = "http://img.timebiz.cn/" + result.First() }, JsonRequestBehavior.AllowGet);
#endif

            return Json(ResultToJson.Json("上传成功", result), JsonRequestBehavior.AllowGet);
        }

        [Route("get_files")]
        public JsonResult GetFiles(string dir = null, string path = "", string order = "id") {
            //var request_data = new folder_model {
            //    method = RequestMethod.GET_FILE, name = dir, bind_no = currentUser.merchant_no
            //};
            dir = "goods";
            var result = new KindEditorFile();
            var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
            string folder = dir + "/";
            var apiResult = oss.ListObjects(DtoHelper.oss_bucketName, folder);

            foreach (var item in apiResult)
                result.file_list.Add(new KindEditorModel {
                    datetime = DateTime.Now, filepath = item.name, filename = Path.GetFileName(item.name),
                    filesize = (int)item.size, filetype = Path.GetExtension(item.name), is_photo = true
                });

            result.moveup_dir_path = "";
            result.current_dir_path = "";
            result.current_url = RequestMethod.token_imgurl;
            ;
            result.total_count = apiResult.Count;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 指定存储空间的文件列表
        /// </summary>
        public class oss_bucket_file {
            /// <summary>
            /// 文件名
            /// </summary>
            /// <value>The key.</value>
            public string name { get; set; }
            public long size { get; set; }
        }

        public class KindEditorFile {
            public KindEditorFile() { file_list = new List<KindEditorModel>(); }
            public string moveup_dir_path = "";
            public string current_dir_path = "";
            public string current_url = "";
            public int total_count { get; set; }
            public List<KindEditorModel> file_list { get; set; }
        }
        public class KindEditorModel {
            public bool is_dir { get; set; }
            public bool has_file { get; set; }
            public int filesize { get; set; }
            public bool is_photo { get; set; }
            public string filetype { get; set; }
            public string filename { get; set; }
            public string filepath { get; set; }
            public DateTime datetime { get; set; }
        }
        #endregion
    }
}
